import * as React from "react";
import { Form, Row, Col, Input, Button, Icon, DatePicker, Select, Table, message, Modal, Spin } from 'antd';
const { confirm } = Modal;
const { Option } = Select;
const { Column } = Table;
import * as moment from 'moment';
import './index.scss';
import { FormComponentProps } from 'antd/lib/form/Form' //获取form表单的interface
import { ListGUID } from '../../config/ListGuid';
import Api from '../../config/api';
import { Item } from "@pnp/sp/items";
import { number, time } from "echarts";
import { Prompt } from "react-router-dom";
import { dynamicsService } from "../../../../../services/services";
import { isHavePermission, isHavePathPermission } from '../../utils/utils'
const layout = {
  labelCol: {
    span: 4,

  },
  wrapperCol: {
    offset: 1,
    span: 19,
  },
}
const tipData = [
  {
    field: '法务审核编号',
    content: '根据规定所属公司和法务受理i年份生成编号',
    remarks: '系统自动生成'
  },
  {
    field: '法务受理日',
    content: '规章制度的首次正式受理日',
    remarks: '必填'
  },
  {
    field: '法务最后回答日',
    content: '法务正式修改案或法务意见书的出具日',
    remarks: '必填'
  },
  {
    field: '规定名称',
    content: '规定的全称（避免空格）',
    remarks: '必填'
  },
  {
    field: '规定编号',
    content: '审查的规定中记载的规定编号',
    remarks: '必填'
  },
  {
    field: '版本号',
    content: '审查的规定中记载的规定版本号',
    remarks: '必填'
  },
  {
    field: '规定所属公司',
    content: '住化集团公司（缩写）',
    remarks: '必填'
  },
  {
    field: '语言',
    content: '规定使用的语言（中，中日，中韩）',
    remarks: '必填'
  },
  {
    field: '问题',
    content: '选项：“有”：有修改意见或有风险提示；“无”：无修改意见',
    remarks: '必填'
  },
  {
    field: '规定分类',
    content: '选择规定的分类（择一）',
    remarks: '必填'
  },
  {
    field: '修改性质',
    content: '选择修改性质（可多选）',
    remarks: '必填'
  },
  {
    field: '审核意见书',
    content: '选项：有/无（默认”无“）',
    remarks: '必填'
  },
  {
    field: '律师审查',
    content: '选项：有/无（默认”无“）',
    remarks: '必填'
  },
  {
    field: '其它',
    content: '其他需要补充登记的信息',
    remarks: '选填'
  },
  {
    field: '决裁编号',
    content: '同FL决裁编号',
    remarks: '系统自动生成'
  },
  {
    field: '审查担当',
    content: '选项默认为编号人（按照选择顺序确认一审、二审、三审）',
    remarks: '必填'
  },
  {
    field: '文件保存',
    content: '法务审核版、审查意见书等的存放地址',
    remarks: '系统自动生成'
  },
  
]
const phoneValidator = (rule: any, value: any, callback: any) => {
  
  
  if (!value) {
    callback('请输入！')
  }
  // 必须总是返回一个 callback，否则 validateFields 无法响应
  callback();
}

// 测试代码，调试API使用
class Regulations extends React.Component<any> {
  constructor(props: any & FormComponentProps) {
    super(props);
  }
  //提交按钮触发
  submit = async (e) => {
    if(e === '提交'|| e === '作废') {
      if(this.state.currentForm &&
        this.state.currentForm.Title.indexOf('DUMY') === -1 &&
        (
          moment(this.state.currentForm.AcceptTime).format('YYYY') !== moment(this.state.form.date).format('YYYY') ||
          this.state.currentForm.BelongsCompany !== this.state.form.we
        )
        ) {
          message.warning('提交失败，当前【受理日】与【规定所属公司】数据与合同编号信息不匹配，请重新检查或点击“生成编号”按钮来生成新的编号。')
          
          return
      }
    }
    await this.setState({
      variable: e == '作废' ? '废弃' : e == '提交' ? '有效' : '草稿'
    })
    
    if (e == '作废') {
      let array = await Api.getFiles(ListGUID.RegulationsLibRelativeUrl + '/' + this.state.form.file)
      if (array.length != 0) {
        message.warning(`存在附件,请先删除附件`, 2)
        return;
      }
    }
    if (e == '保存草稿') {
      //this.getSubmit()
      this.warning(e)
    } else {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          //this.getSubmit()
          e == '提交' ? e = '保存' : e = e;
          this.warning(e)
        }
      });
    }

  };
  //初始化数据
  initialization = () => {
    let { form } = this.state;
    form = {
      // 法务受理日
      date: null,
      // 法务最后回答日
      date1: null,
      // 语言
      language: undefined,
      // 规定名称
      theContract: null,
      // 规定编号
      otherSide: null,
      // 社内依赖者名
      community: null,
      // 其他
      other: null,
      // 法务审核编号
      contract: '',
      // 决裁编号
      cutNumber: '',
      // 审查担当
      reviewOn: [],
      // 文件保存
      file: null,
      //下拉选择
      //问题
      problem: undefined,
      //性质
      nature: undefined,
      //规定所属公司
      we: undefined,
      //修改性质
      qualifications: undefined,
      qualificationss: [],
      //律师审查
      examination: undefined,
      // 版本号
      versionNum: null,
      //审查担当
      reviewOnxuan: [],
      //审查担当
      reviewOnxuans: undefined,
      enclosurelist: [],
       //意见书
      proposal:undefined,
    }
    this.setState({
      form,
      wedisabled: false,
      JudgmentVariable: null,
      JudgmentVariableID: null,
      DraftNo: null,
      discardID:null,
      time:null
    })
    this.props.form.setFieldsValue({
      contract: '',
      data: null,
      theContract: null,
      text: undefined,
      data1: null
    })
  };
  // 关闭按钮触发
  // shutDown = () => {
  //   confirm({
  //     centered: true,
  //     title: '温馨提示',
  //     content: `是否关闭该页面,关闭该页面未提交数据清空?`,
  //     okText: '确认',
  //     cancelText: '取消',
  //     onOk: () => { location.href = '#/Dashboard' }
  //   });
  // }


  // 法务受理日
  onChange = (date, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        date: dateString
      }
    })
  }
  // 法务最后回答日
  onChange1 = (date, dateString) => {
    this.setState({
      form: {
        ...this.state.form,
        date1: dateString
      }
    })
  }
  disabledDate = time => {
    if (this.state.JudgmentVariable != null) {
      if (this.state.form.contract.indexOf('DUMY') === -1) {
        var timeYear = time.get('year');  //当前年
        var currentYear =this.state.time; //今年
        return timeYear != currentYear;
      } else {
        
      }
    }
  };
  state = {
    tipVisible: false,
    AuthorId: JSON.parse(sessionStorage.getItem('userInfo')).Id,
    AuthorName: JSON.parse(sessionStorage.getItem('userInfo')).Title,
    currentForm: null,
    loading: false,

    regulationsId: '',
    backPage: '', // 返回的页面
    //表单数据对象
    form: {
      // 法务受理日
      date: null,
      // 法务最后回答日
      date1: null,
      // 语言
      language: undefined,
      // 规定名称
      theContract: null,
      // 规定编号
      otherSide: null,
      // 社内依赖者名
      community: null,
      // 其他
      other: null,
      // 法务审核编号
      contract: '',
      // 决裁编号
      cutNumber: '',
      // 审查担当
      reviewOn: [],
      // 文件保存
      file: null,
      //下拉选择
      //问题
      problem: undefined,
      //性质
      nature: undefined,
      //规定所属公司
      we: undefined,
      //修改性质
      qualifications: undefined,
      qualificationss: [],
      //律师审查
      examination: '无',
      // 版本号
      versionNum: null,
      //审查担当
      reviewOnxuan: [],
      //审查担当
      reviewOnxuans: undefined,
      enclosurelist: [],
       //意见书
       proposal:'无',

    },
    //问题
    problemList: [],
    // 语言
    languageList:[],
    //我方
    weList: [],
    //律师审查
    LawyerList: [],
    //审查担当
    personreviewList: [],
    //规定分类
    SpecifyList: [],
    //修改性质
    NatureList: [],
    //状态
    variable: '',
    //变量
    JudgmentVariable: null,
    JudgmentVariableID: number,
    fujian: null,
    wedisabled: false,
    when: false,
    DraftNo: null,
    //废弃编号id
    discardID:null,
    time:null
  }
  //跳转
  toOtherPage = (e) => {
    location.href = e
  }
  handleCancel = () => {
    this.setState({
      tipVisible: false
    })
  }
  onBlur(e) {
    let paten = /^[A-Za-z]+$/g;
    if(!paten.test(this.state.form.we)){
      message.warning('请输入字母',2);
      setTimeout(()=>{
        this.setState({
          form: {
            ...this.state.form,
            we : undefined,
          }
        })
        
        this.props.form.setFieldsValue({
          text: undefined,
        })
      },100)
      return;
    }
    
    this.props.form.setFieldsValue({
      text: this.state.form.we
    })
  }
  // 输入框改变赋值
  change(e, key) {
    if (key == 'we') {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value.toUpperCase()
        }
      })
      
    } else {
      this.setState({
        form: {
          ...this.state.form,
          [key]: e.target.value
        }
      })
    }


  }
  // 下拉框改变赋值
  handleSelectChange(e, key) {
    this.setState({
      form: {
        ...this.state.form,
        [key]: e
      }
    })
  }
  // 下拉框改变赋值
  handleSelectChanges(e, v, key) {
    var array = []
    var arrays = []
    
    v.forEach(element => {
      array.push(element.key)
      arrays.push(`${element.props.value}#${element.props.children}`)
    });
    this.setState({
      form: {
        ...this.state.form,
        reviewOn: array.join(","),
        reviewOnxuans: arrays.join(';'),
        [key]: e
      }
    })
    // 
  }

  // 下拉框改变赋值
  handleSelectChangess(e, v, key) {
    var array = []

    v.forEach(element => {
      array.push(element.key)
      // arrays.push(`${element.props.value}#${element.props.children}`)
    });
    
    let size = array.join(',')
    
    this.setState({
      form: {
        ...this.state.form,
        qualifications: array.join(","),
        [key]: e
      }
    })
    // 
  }
  //提示框
  warning = (e) => {
    confirm({
      centered: true,
      title: '温馨提示',
      content: `是否`+ e +`?`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => { this.getSubmit() }
    });
  };
  public async componentDidUpdate(prevProps, prevState) {
    // 
    // if (this.state.form.date == null || this.state.form.date == '' && this.state.form.date1 == null || this.state.form.date1 == '' &&
    //   this.state.form.language == null || this.state.form.language == '' && this.state.form.theContract == null || this.state.form.theContract == '' &&
    //   this.state.form.otherSide == null || this.state.form.otherSide == '' && this.state.form.community == null || this.state.form.community == '' &&
    //   this.state.form.other == null || this.state.form.other == '' &&
    //   this.state.form.contract == '' && this.state.form.cutNumber == '' && this.state.form.reviewOn == null || this.state.form.reviewOn == '' &&
    //   this.state.form.file == null || this.state.form.file == '' &&
    //   this.state.form.problem == undefined || this.state.form.problem == '' && this.state.form.nature == undefined || this.state.form.nature == '' &&
    //   this.state.form.we == undefined || this.state.form.we == '' && this.state.form.qualifications == undefined || this.state.form.qualifications == '' &&
    //   this.state.form.examination == undefined || this.state.form.examination == '' && this.state.form.reviewOnxuan.length == 0 && this.state.form.reviewOnxuans == undefined || this.state.form.reviewOnxuans == '' && this.state.form.enclosurelist.length == 0) {
    //   if (!this.state.when) return;
    //   let self = this;
    //   setTimeout(() => {
    //     self.setState({ when: false });
    //   })
    // } else {
    //   if (this.state.when) return;
    //   let self = this;
    //   setTimeout(() => {
    //     self.setState({ when: true });
    //   })
    // }
  }
  //动态更新绑定数据
  public async componentDidMount() {
    isHavePathPermission()
    this.getTest();// 测试代码，调试API使用
    this.setButtonsEventHandlers();
    this.setState({
      AuthorId: JSON.parse(sessionStorage.getItem('userInfo')).Id,
      AuthorName: JSON.parse(sessionStorage.getItem('userInfo')).Title
    })
    let title = this.props.location.state;
    if (title) {
      // dynamicsService.UpdateListFileNames({id: title.id})
      this.getedit(title.id)
      this.setState({
        regulationsId: title.id,
        backPage: title.backPage
      })
    }
  }
  //编号 生成 我方+年+3位自增长序号 
  //   合同/{年度}/{公司别}/{合同编号} [{申请书序列号}]
  public render(): React.ReactElement {

    const { getFieldDecorator } = this.props.form;
    const prefixSelector =
      <Select allowClear  style={{ width: 130 }}>
        {
          this.state.personreviewList.map(element => {
            return <Option value={element} key={element}>{element}</Option>
          })
        }
      </Select>

    return (
      <div className='box'>
        {/* <Prompt
            when={this.state.when}
            message={(location) =>
              "当前页面有未保存的内容,是否离开？"
            }
          /> */}
          <Spin spinning={this.state.loading}>
          <div className='box_content'>
          <Row align="middle" justify="end">
            <Col span={24}>
              <div className='flex'>
                <div className="heTong"></div>
                <div className='het'>规章制度编号<span onClick={() => this.setState({tipVisible: true})}>(填写说明)</span></div>
              </div>
            </Col>
          </Row>
          <Row type="flex" justify="end">
            {
                isHavePermission('AddContractNo/tocontractversion') ? <Col span={1}> <Button type="default" className="Button_4" onClick={() => { this.toOtherPage("#/RegulationsVersion") }}>版本号</Button></Col> : null
              }
            {
                isHavePermission('Regulations/abandon') ? <Col span={1}  offset={1}> <Button type="default" className="Button_1" disabled={this.state.form.contract.indexOf('DUMY') !== -1  ? true : false} onClick={() => { this.submit("作废") }}>作废</Button></Col> : null
              }
            {
                isHavePermission('Regulations/submit') ? <Col span={1}  offset={1}> <Button type="primary" className="Button_2" onClick={() => { this.submit("提交") }}>提交</Button></Col> : null
              }
            {
                isHavePermission('Regulations/draft') ? <Col span={1}  offset={1}> <Button type="primary" className="Button_3" disabled={this.state.form.contract && this.state.form.contract.indexOf('DUMY') === -1 ? true : false} onClick={() => { this.submit("保存草稿") }}>草稿</Button></Col> : null
              }
            {
                isHavePermission('Regulations/close') ? <Col span={1}  offset={1}> <Button type="primary" onClick={this.shutDown}>关闭</Button></Col> : null
              }
              {
                this.state.regulationsId != '' ? <Col span={1} offset={1}>
              
                <Button type="primary" onClick={()=>{ this.props.history.push({pathname: this.state.backPage, state: {isBack: 1}}) }}>返回</Button>
              
            </Col> : ''
              }
            
          </Row>
          <div className="top"></div>
          <Form {...layout} name='login' layout="inline">
            <Row type="flex" justify="space-between">
              <Col span={11}>
                <Form.Item label='法务审核编号' labelAlign="right">
                  {
                    getFieldDecorator('contract', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true,
                        }
                      ],
                      initialValue: this.state.form.contract
                    })(<Input  allowClear disabled placeholder="请输入" />)
                  }
                </Form.Item>
              </Col>
              <Col span={2}>
                <Form.Item>
                  {
                    isHavePermission('Regulations/createnum') ? <Button type="primary" className="Button_3"  onClick={this.generateNumber}>生成编号</Button> : null
                  }

                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='问题' labelAlign="right">
                  <Select allowClear 
                    placeholder="请选择"
                    value={this.state.form.problem}
                    onChange={(event) => { this.handleSelectChange(event, "problem") }}
                  >
                    {
                      this.state.problemList.map(element => {
                        return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='法务受理日' labelAlign="right">
                  {
                    getFieldDecorator('data', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true
                        }
                      ],
                    })(<DatePicker allowClear  style={{ width: '100%' }} placeholder="请选择年份" onChange={this.onChange} format='YYYY/MM/DD' />)
                  }

                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='规定分类' labelAlign="right">
                  <Select allowClear 
                    placeholder="请选择内容"
                    value={this.state.form.nature}
                    onChange={(event) => { this.handleSelectChange(event, "nature") }}
                  >
                    {
                      this.state.SpecifyList.map(element => {
                        return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='法务最后回答日' labelAlign="right">
                  {
                    getFieldDecorator('data1', {
                    })(<DatePicker allowClear  style={{ width: '100%' }} placeholder="请选择年份" onChange={this.onChange1} format='YYYY/MM/DD' />)
                  }
                  {/* <DatePicker allowClear  value={this.state.form.date1 == null? this.state.form.date1 : moment(this.state.form.date1)} style={{ width: '100%' }} placeholder="请选择年份" onChange={this.onChange1} format='YYYY/MM/DD' /> */}
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='修改性质' labelAlign="right">
                  <Select allowClear  mode='multiple'
                    placeholder="请选择"
                    value={this.state.form.qualificationss}
                    onChange={(event, value) => { this.handleSelectChangess(event, value, "qualificationss") }}
                    maxTagCount={2}
                  >
                    {
                      this.state.NatureList.map(element => {
                        return <Option value={element.Title} key={element.Title}>{element.Title}</Option>
                      })
                    }
                  </Select>


                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='规定名称' labelAlign="right">
                  {
                    getFieldDecorator('theContract', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true
                        }
                      ],
                      initialValue: this.state.form.theContract
                    })(<Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "theContract") }} />)
                  }
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='审核意见书' labelAlign="right">
                  <Select allowClear 
                    placeholder="请选择"
                    value={this.state.form.proposal}
                    onChange={(event) => { this.handleSelectChange(event, "proposal") }}
                  >
                     <Option value='有' >有</Option>
                     <Option value='无' >无</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='规定编号' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "otherSide") }} value={this.state.form.otherSide} />
                </Form.Item>
              </Col>
              
              <Col span={11} >
                <Form.Item label='律师审查' labelAlign="right">
                  <Select allowClear 
                    placeholder="请选择"
                    value={this.state.form.examination}
                    onChange={(event) => { this.handleSelectChange(event, "examination") }}
                  >
                    {
                      this.state.LawyerList.map(element => {
                        return <Option value={element.Title} key={element.ID}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>

                {/* 版本号？？ */}
              <Col span={11} >
                <Form.Item label='版本号' labelAlign="right">
                  <Input allowClear value={this.state.form.versionNum} onChange={(event) => { this.change(event, "versionNum") }} placeholder='请输入' />
                </Form.Item>
              </Col>

              <Col span={11}>
                <Form.Item label='其他' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "other") }} value={this.state.form.other} />
                </Form.Item>
              </Col>



              <Col span={11}>
                <Form.Item label='规定所属公司' labelAlign="right">
                  {
                    getFieldDecorator('text', {
                      rules: [
                        {
                          validator: phoneValidator,
                          required: true
                        }
                      ],
                      initialValue: this.state.form.we
                    })(
                      <Select allowClear 
                      onChange={(event) => { this.handleSelectChange(event, "we") }}
                      placeholder="请选择"
                    >
                      {
                        this.state.weList.map(element => {
                          return <Option value={element.Title} key={element.Title}>{element.Title}</Option>
                        })
                      }
                    </Select>
                    //<Input allowClear placeholder="请输入内容" onBlur={(event) => { this.onBlur(event) }} style={{ textTransform: 'uppercase' }} onChange={(event) => { this.change(event, "we") }} disabled={this.state.wedisabled} />
                    )
                  }
                </Form.Item>
              </Col>

              <Col span={11} >
                <Form.Item label='决裁编号' labelAlign="right">
                  <Input allowClear disabled value={this.state.form.cutNumber} placeholder='请输入' />
                </Form.Item>
              </Col>

              

              {/* <Col span={11} >
                <Form.Item label='决裁编号' labelAlign="right">
                  <Input allowClear disabled value={this.state.form.cutNumber} />
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item label='其他' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "other") }} value={this.state.form.other} />
                </Form.Item>
              </Col> */}
              <Col span={11}>
                <Form.Item label='依赖者名' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" onChange={(event) => { this.change(event, "community") }} value={this.state.form.community} />
                </Form.Item>
              </Col>
              <Col span={11} >
                <Form.Item label="审查担当">
                  <Input.Group compact>
                    <Select allowClear  mode='multiple' placeholder="请选择" style={{ width: '35%' }} value={this.state.form.reviewOnxuan}
                      onChange={(event, value) => { this.handleSelectChanges(event, value, "reviewOnxuan") }} maxTagCount={1}>
                      {
                        this.state.personreviewList.map(element => {
                          return <Option value={element.ID} key={element.Title}>{element.Title}</Option>
                        })
                      }
                    </Select>
                    <Input allowClear style={{ width: '65%' }}
                      placeholder="请输入内容" disabled value={this.state.form.reviewOn} />
                  </Input.Group>
                </Form.Item>
              </Col>

              
              <Col span={11} >
                <Form.Item label='语言' labelAlign="right">
                  <Select allowClear 
                    placeholder="请选择语言"
                    value={this.state.form.language}
                    onChange={(event) => { this.handleSelectChange(event, "language") }}
                  >
                    {
                      this.state.languageList.map(element => {
                        return <Option value={element.Title} key={element.Title}>{element.Title}</Option>
                      })
                    }
                  </Select>
                </Form.Item>
              </Col>
              
              <Col span={11} >
                <Form.Item label='文件保存' labelAlign="right">
                  <Input allowClear value={this.state.form.file} onClick={this.getFilds} readOnly />
                  {
                    isHavePermission('Regulations/upload') ? <Input allowClear placeholder="附件" multiple value={this.state.fujian} id="fileUploadInput" type="file" name="myfile" style={{ display: "none" }} /> : null
                  }

                </Form.Item>
              </Col>


              {/* <Col span={11} >
                <Form.Item label='语言' labelAlign="right">
                  <Input allowClear placeholder="请输入内容" value={this.state.form.language} onChange={(event) => { this.change(event, "language") }} />
                </Form.Item>
              </Col> */}

              

              
            </Row>

          </Form>
        </div>
          </Spin>
          <Modal
          title="填写说明"
          visible={this.state.tipVisible}
          width={'50%'}
          footer={false}
          onCancel={this.handleCancel}
          className="tipsModel1"
        >
          <Table size="small" dataSource={tipData} bordered pagination={false} footer={() => <p>版本号：指同一规定再次审查时，在“-0”的基础上累加编号。为避免编错号码，在版本号“法务审核编号”处输入第一次审查规定法务编号“-0”前的编号并点击空白处后会显示第一次审查的规定信息，信息无误的点击”匹配“，生成版本号。（只限定稿，审核中交涉多次不必重新编号））</p>}>
              <Column title="字段" dataIndex="field" key="field" width='150px' render={(_: any, record:any) => (
                <span style={{color: '#333'}}>{record.field}</span>
              )} />
              <Column title="填写内容" dataIndex="content" key="content" />
              <Column title="备注" dataIndex="remarks" key="remarks" width='150px' align="center" render={(_: any, record:any) => (
                <span style={{color: record.remarks === '必填' ? 'red' : record.remarks === '系统自动生成' ? '#87d068' : 'initial'}}>{record.remarks}</span>
              )} />
          </Table>
        </Modal>
      </div>
    )

  }
  private setButtonsEventHandlers(): void {
    let fileUpload = document.getElementById('fileUploadInput');
    if (fileUpload) {
      fileUpload.addEventListener('change', () => {
        this.fileinputChange(fileUpload);
      });
    }
  }
  getFilds = () => {
    if (this.state.form.file) {
      // const filedom = document.getElementById('fileUploadInput');
      // filedom.click()
      
      dynamicsService.UpdateListFileNames({dataid: this.state.currentForm.id, listguid: ListGUID.Regulations, fileaddress: this.state.currentForm.FileAddress}).then(() => {
        if(isHavePermission('Regulations/todocumentlibrary')) {
          if(this.state.form.contract.indexOf('DUMY') === -1) {
            window.open(ListGUID.Domain + ListGUID.RegulationsLibRelativeUrl+'/'+this.state.form.file)
          } else {
            window.open(ListGUID.Domain + ListGUID.DumyLibRelativeUrl+'/'+this.state.form.file)
          }
          
        }
      })
      
      return;
    }
    message.warning('暂无上传路径', 2)
  }
  //循环
  getloop = async (item) => {
    var fileData = item;
    let fSize = fileData.size
    let fileName = fileData.name
    var maxSize = 20 * 1024 * 1024; //限制20M
    if (fSize > maxSize) {
      message.warning(`${fileName}文件内容太大，上传失败，请检查文件后重新上传!`, 2)
      return;
    }
    //判断空文件
    if (fSize == 0) {
      //空文件
      message.warning(`${fileName}的文件内容为空，请检查文件后重新上传!`, 2)
      return;
    }

    //判断文件名称合法
    if (fileName.indexOf('.') > -1 || fileName.indexOf('%') > -1 || fileName.indexOf('#') > -1 || fileName.indexOf('+') > -1) {
      //排除 .
      if (fileName.indexOf('.') > -1) {
        let firstCodePosition = fileName.indexOf('.');
        let lastCodePosition = fileName.lastIndexOf('.');
        if (firstCodePosition != lastCodePosition) {
          //位置不同，有多个 
          message.warning(`${fileName}文件名称包含特殊字符‘.’，不允许上传，请修改文件名称后重新上传`, 2)
          return;
        }
      }

      //排除 % # +
      if (fileName.indexOf('%') > -1 || fileName.indexOf('#') > -1 || fileName.indexOf('+') > -1) {
        message.warning(`${fileName}文件名称包含特殊字符‘%、#、+’，不允许上传，请修改文件名称后重新上传`, 2)
        return;
      }
    }

    //判断文件名称超长       
    if (fileName.length >= 44) {
      message.warning(`${fileName}文件名称超过40个字符，请修改文件名称后重新上传`, 2)
      return;
    }
    let array = await Api.getFiles(ListGUID.RegulationsLibRelativeUrl + '/' + this.state.form.file)
    if (array.length != 0) {
      for (let j = 0; j < array.length; j++) {
        if (fileName == array[j].Name) {
          message.warning(`${fileName}文件名已在申请中或文档中心已存在，请勿重复申请`, 2)
          return;
        }
      }
    }
    let url = ListGUID.RegulationsLibRelativeUrl + '/' + this.state.form.file
    let parme = Api._addfiles(fileData, url)
    if (parme) {
      var arrays = [];
      arrays.push(fileName)
      arrays = this.state.form.enclosurelist.concat(arrays)
      this.setState({
        form: {
          ...this.state.form,
          enclosurelist: arrays
        }
      })
      message.success(`${fileName}文件上传成功`, 2)
      
    }
  }
  //上传附件
  fileinputChange = async (event) => {
    for (let i = 0; i < event.files.length; i++) {
      this.getloop(event.files[i])
    }
  }
  public async getTest() {

    var param7 = {
      Guid: ListGUID.ReviewOn //审查担当
    };
    let Person = await Api._getModel(param7);
    var param1 = {
      Guid: ListGUID.ReviseNature //修改性质
    }

    let Nature = await Api._getModel(param1);
    var param2 = {
      Guid: ListGUID.RegulationsType //规定分类
    }

    let Specify = await Api._getModel(param2);

    var param3 = {
      Guid: ListGUID.LawerReview //律师审查
    };
    let Lawyerreview = await Api._getModel(param3);

    var param5 = {
      Guid: ListGUID.Question // 问题 
    };
    let Problem = await Api._getModel(param5);
    var param4 = {
      Guid: ListGUID.Companies // 公司设置
    };
    let Companysettings = await Api._getModel(param4);
    // let Companysettings = JSON.parse(sessionStorage.getItem('userDataPer')).PermissionCompany
    Person = !this.state.regulationsId ? Person.filter(i => !i.Title.includes('-历史')) : Person;
    const userList = JSON.parse(localStorage.getItem('usersList'));
    Person.forEach(async item => {
      // let informationid = await Api.GetUserById(item.ReviewUserId)
      let informationid = userList.filter(i => i.id === item.ReviewUserId)
      if (informationid && informationid.length > 0) {
        item.Title = informationid.Title
      }
      
      return
    });
    let languageList = [{Title:'中'},{Title:'中日'},{Title:'中韩'}]
    setTimeout(() => {
      this.setState({
        //规定分类
        SpecifyList: Specify,
        //修改性质
        NatureList: Nature,
        LawyerList: Lawyerreview,
        problemList: Problem,
        languageList:languageList,
        personreviewList: Person,
        weList: Companysettings.filter(i => !i.Title.includes('-历史')),
      }, () => {
        if(!this.state.currentForm) {
          this.getcurrentUser()
        }
      })
    }, 300)
    // _that.state.problemList = Departmentlst

  }
  //默认登陆人
  public async getcurrentUser() {
    let { form } = this.state;
    //获取当前登录人
    let Loggedby = await Api._getcurrentUser();
    this.state.personreviewList.forEach(element => {
      if (Loggedby.Id === element.ReviewUserId) {
        form.reviewOnxuan = []
        form.reviewOnxuan.push(element.Id)
        form.reviewOn = element.Title
        form.reviewOnxuans = `${element.Id}#${element.Title}`
      }
    });
    this.setState({
      form
    })

  }
  //提交合同 草稿 作废
  public async getSubmit() {
    var date = new Date
    var year = date.getFullYear();
    
    // var param = {
    //   Guid: ListGUID.Regulations,
    //   Filter: `Title eq '${this.state.form.contract}'`
    // };
    // let Persons = await Api._getModel(param);


    if(this.state.currentForm) {
      this.UpdateData(this.state.currentForm.ItemId)
    } else {
      if(this.state.variable === '草稿') {
        this.AddData()
      }
    }
    this.setState({
      loading: false
    })
    /**--------------------- */

    // let params: any = [
    //   {
    //     logic: "and",
    //     where: [
    //       {
    //         key: 'Title',
    //         filterType: "Eq",
    //         value: this.state.form.contract
    //       }
    //     ]
    //   }
    // ];
    // let data = await Api._getPaged2({ Guid: ListGUID.Regulations, PageSize: 100000, PageIndex: 1, FilterL: params })
    // let Persons = data.data;
    // if (Persons.length != 0) {
    //   //  添加新合同
    //   var pa = {
    //     Guid: ListGUID.Regulations,  //变更申请
    //     ItemId: Persons[0].ID,
    //     Obj: {
    //       Title: this.state.form.contract, //合同编号
    //       AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
    //       Language: this.state.form.language,//语言
    //       Question: this.state.form.problem,//问题
    //       LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
    //       RegulationsCatalog: this.state.form.nature,  //规定分类
    //       RegulationsName: this.state.form.theContract,  //规定名称
    //       ModifyNature: this.state.form.qualifications, //修改性质
    //       RegulationsNum: this.state.form.otherSide, //规定编号
    //       LawyerReview: this.state.form.examination,//律师审查
    //       BelongsCompany: this.state.form.we, //规定所属公司
    //       RuleNumber: this.state.form.cutNumber,//决裁编号
    //       RelierName: this.state.form.community,//社内依赖者
    //       ReviewOn: this.state.form.reviewOnxuans,//审查担当
    //       Other: this.state.form.other,//其它 
    //       HasReviewOpinion:this.state.form.proposal,//申请书
    //       SerialNum: this.state.form.contract == '' ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)), //流水号
    //       AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
    //       VersionNum: this.state.form.versionNum,// 版本号
    //       RegulationsStatus: this.state.variable,//状态
    //       FileAddress: this.state.form.file,//文件保存路径
    //       Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
    //     }
    //   };
    //   //废弃编号启用
    //   if (this.state.JudgmentVariable == '废弃') {
    //     if (this.state.variable == '草稿') {
    //       var param = {
    //         Guid: ListGUID.Regulations,
    //         Filter: `RegulationsStatus eq '草稿' and AcceptYear eq '${Number(year)}' `
    //       };
    //       let Persons = await Api._getModel(param);
    //       if (Persons.length != 0) {
    //         let array = []
    //         Persons.forEach(element => {
    //           array.push({
    //             Title: Number(element.Title.substr(-3)),
    //             ID: element.ID
    //           })
    //         });
    //         array.sort(function (a, b) {
    //           return a.Title - b.Title  //正序
    //         })
    //         pa.Obj.Title = 'DUMYGD' + Number(year) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //         pa.Obj.AcceptYear = Number(year)
    //       } else {
    //         pa.Obj.Title = 'DUMYGD' + Number(year) + "001"
    //         pa.Obj.AcceptYear = Number(year)
    //       }

    //     }
    //     let parm = {
    //       Guid: pa.Guid,
    //       ItemId: Number(this.state.JudgmentVariableID),
    //       Obj: pa.Obj
    //     }

    //     var UPdeta = await Api._updateData(parm)
    //     this.initialization()
    //     return;
    //   } else if (this.state.JudgmentVariable == '草稿') {
    //     if (this.state.variable == '草稿') {
    //       pa.Obj.Title = this.state.DraftNo
    //       pa.Obj.AcceptYear = Number(year)
    //     }
    //     let parm = {
    //       Guid: pa.Guid,
    //       ItemId: Number(this.state.JudgmentVariableID),
    //       Obj: pa.Obj
    //     }
    //     
    //     var UPdeta = await Api._updateData(parm)
    //     //草稿启用废弃编号 删除废弃记录
    //     if(this.state.DraftNo != null){
    //       let params = {
    //         ListName: "Regulations",//List表名
    //         ItemId: this.state.discardID,//要删除的List item的id
    //       };
    //       
    //       let data = await Api._deleteData(params);
    //       
    //     }
    //     this.initialization()
    //     return;
    //   }
    //   if (this.state.variable == '草稿') {
    //     var param = {
    //       Guid: ListGUID.Regulations,
    //       Filter: `RegulationsStatus eq '草稿' and AcceptYear eq '${Number(year)}'`
    //     };
    //     let Persons = await Api._getModel(param);
    //     if (Persons.length != 0) {
    //       let array = []
    //       Persons.forEach(element => {
    //         array.push({
    //           Title: Number(element.Title.substr(-3)),
    //           ID: element.ID
    //         })
    //       });
    //       array.sort(function (a, b) {
    //         return a.Title - b.Title  //正序
    //       })
    //       pa.Obj.Title = 'DUMYGD' + Number(year) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //       pa.Obj.AcceptYear = Number(year)
    //     } else {
    //       pa.Obj.Title = 'DUMYGD' + Number(year) + "001"
    //       pa.Obj.AcceptYear = Number(year)
    //     }

    //   }

    //   var result = await Api._updateData(pa);
    //   this.initialization()
    // } else {
    //   var content = {
    //     Guid: ListGUID.Regulations,  //变更申请
    //     Obj: {
    //       Title: this.state.form.contract, //合同编号
    //       AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
    //       Language: this.state.form.language,//语言
    //       Question: this.state.form.problem,//问题
    //       LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
    //       RegulationsCatalog: this.state.form.nature,  //规定分类
    //       RegulationsName: this.state.form.theContract,  //规定名称
    //       ModifyNature: this.state.form.qualifications, //修改性质
    //       RegulationsNum: this.state.form.otherSide, //规定编号
    //       LawyerReview: this.state.form.examination,//律师审查
    //       BelongsCompany: this.state.form.we, //规定所属公司
    //       RuleNumber: this.state.form.cutNumber,//决裁编号
    //       RelierName: this.state.form.community,//社内依赖者
    //       ReviewOn: this.state.form.reviewOnxuans,//审查担当
    //       Other: this.state.form.other,//其它 
    //       HasReviewOpinion:this.state.form.proposal,//申请书
    //       SerialNum: this.state.form.contract == '' ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)), //流水号
    //       AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
    //       VersionNum: this.state.form.versionNum,// 版本号
    //       RegulationsStatus: this.state.variable,//状态
    //       FileAddress: this.state.form.file,//文件保存路径
    //       Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
    //     }
    //   };
    //   if (this.state.JudgmentVariable == '草稿') {
    //     if (this.state.variable == '草稿') {
    //       content.Obj.Title = this.state.DraftNo
    //       content.Obj.AcceptYear = Number(year)
    //     }
    //     let parm = {
    //       Guid: content.Guid,
    //       ItemId: Number(this.state.JudgmentVariableID),
    //       Obj: content.Obj
    //     }
    //     
    //     
    //     var UPdeta = await Api._updateData(parm)
    //     this.initialization()
    //     return;
    //   }
    //   if (this.state.variable == '草稿') {
    //     var param = {
    //       Guid: ListGUID.Regulations,
    //       Filter: `RegulationsStatus eq '草稿' and AcceptYear eq '${Number(year)}'`
    //     };
    //     let Persons = await Api._getModel(param);
    //     if (Persons.length != 0) {
    //       let array = []
    //       Persons.forEach(element => {
    //         array.push({
    //           Title: Number(element.Title.substr(-3)),
    //           ID: element.ID
    //         })
    //       });
    //       array.sort(function (a, b) {
    //         return a.Title - b.Title  //正序
    //       })
    //       content.Obj.Title = 'DUMYGD' + Number(year) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3)
    //       content.Obj.AcceptYear = Number(year)
    //     } else {
    //       content.Obj.Title = 'DUMYGD' + Number(year) + "001"
    //       content.Obj.AcceptYear = Number(year)
    //     }

    //   }
    //   var result = await Api._saveaddDataGuid(content);
    //   this.initialization()

    // }

     /**--------------------- */
  }
  // 更新数据
  UpdateData = async (id) => {
    this.setState({
      loading: true
    })
    let parm = {
      Guid: ListGUID.Regulations,
      ItemId: id,
      Obj: {
        Title: this.state.form.contract, //合同编号
        AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
        Language: this.state.form.language,//语言
        Question: this.state.form.problem,//问题
        LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
        RegulationsCatalog: this.state.form.nature,  //规定分类
        RegulationsName: this.state.form.theContract,  //规定名称
        ModifyNature: this.state.form.qualificationss && this.state.form.qualificationss.join(','), //修改性质
        RegulationsNum: this.state.form.otherSide, //规定编号
        LawyerReview: this.state.form.examination,//律师审查
        BelongsCompany: this.state.form.we, //规定所属公司
        RuleNumber: this.state.form.cutNumber,//决裁编号
        RelierName: this.state.form.community,//社内依赖者
        ReviewOn: this.state.form.reviewOnxuans,//审查担当
        Other: this.state.form.other,//其它 
        HasReviewOpinion:this.state.form.proposal,//申请书
        SerialNum: this.state.form.contract == '' ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)), //流水号
        AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
        VersionNum: this.state.form.versionNum,// 版本号
        RegulationsStatus: this.state.variable || '有效',//状态
        // FileAddress: this.state.form.file,//文件保存路径
        // Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';')
      }
    }
    // await Api._updateData(parm)
    parm.Obj['AuthorName'] = this.state.AuthorName;
    parm.Obj['ItemId'] = id;
    let response = await dynamicsService.UpdateRegulation(parm.Obj)
    if(response.code === 200) {
      let reviewOnxuan = []
      let reviewOn = []
      if (response.data.ReviewOn != null) {
        if (response.data.ReviewOn.indexOf(';') != -1) {
          let arrays = response.data.ReviewOn.split(';')
          for (let i = 0; arrays.length > i; i++) {
            reviewOnxuan.push(Number(arrays[i].split('#')[0]))
            reviewOn.push(arrays[i].split('#')[1])
          }
        } else {
          reviewOnxuan.push(Number(response.data.ReviewOn.split('#')[0]))
          reviewOn.push(response.data.ReviewOn.split('#')[1])
        }
      }
    let form = {
        contract: response.data.Title, //编号
        date: response.data.AcceptTime == null ? null : moment(response.data.AcceptTime).format('YYYY/MM/DD'),//法务受理日
        language: response.data.Language,//语言
        problem: response.data.Question,//问题
        date1: response.data.LastAnswerTime == null ? null : moment(response.data.LastAnswerTime).format('YYYY/MM/DD'),//法务最后回答
        nature: response.data.RegulationsCatalog,//规定分类
        theContract: response.data.RegulationsName,//规定名称
        qualificationss: response.data.ModifyNature ? response.data.ModifyNature.split(',') : [],//修改性质
        otherSide: response.data.RegulationsNum,//规定编号
        examination: response.data.LawyerReview,//律师审查 
        we: response.data.BelongsCompany, //规定所属公司
        cutNumber: response.data.RuleNumber,//决裁编号
        community: response.data.RelierName,//社内依赖者
        reviewOnxuans: response.data.ReviewOn,//审查担当
        file: response.data.FileAddress,//文件保存路径
        other: response.data.Other,//其它 
        proposal:response.data.HasReviewOpinion,//申请书
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        versionNum: response.data.VersionNum,// 版本号
        // enclosurelist: response.data.Names == null ? [] : response.data.Names.split(';')
    }
    this.props.form.setFieldsValue({
      contract: response.data.Title
    })
    this.setState({
      currentForm: response.data
    })
    if(!response.title.includes('DUMY')) {
      this.setState({
        form: form,
      })
    }
    this.setState({
      loading: false
    })
    } else {
      this.setState({
        loading: false
      })
      message.warning(response.msg);
    }
    
   
  }
  // 新增数据
  AddData = async () => {
    this.setState({
      loading: true
    })
    let parm = {
      Guid: ListGUID.Regulations,
      Obj: {
        // Title: this.state.form.contract, //合同编号
        AcceptTime: this.state.form.date == null ? null : this.state.form.date,//法务受理日
        Language: this.state.form.language,//语言
        Question: this.state.form.problem,//问题
        LastAnswerTime: this.state.form.date1 == null ? null : this.state.form.date1,//法务最后回答
        RegulationsCatalog: this.state.form.nature,  //规定分类
        RegulationsName: this.state.form.theContract,  //规定名称
        ModifyNature: this.state.form.qualificationss ? this.state.form.qualificationss.join(',') : '', //修改性质
        RegulationsNum: this.state.form.otherSide, //规定编号
        LawyerReview: this.state.form.examination,//律师审查
        BelongsCompany: this.state.form.we, //规定所属公司
        RelierName: this.state.form.community,//社内依赖者
        ReviewOn: this.state.form.reviewOnxuans,//审查担当
        Other: this.state.form.other,//其它 
        HasReviewOpinion:this.state.form.proposal,//申请书
        SerialNum: this.state.form.contract == '' ? null : Number(this.state.form.contract.substring(0, this.state.form.contract.lastIndexOf('-')).substr(-3)), //流水号
        AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
        VersionNum: this.state.form.versionNum,// 版本号
        RegulationsStatus: this.state.variable || '有效',//状态
        // FileAddress: this.state.form.file,//文件保存路径
        // Names: this.state.form.enclosurelist.length == 0 ? null : this.state.form.enclosurelist.join(';'),
      }
    }
    parm.Obj['AuthorId'] = this.state.AuthorId;
    parm.Obj['AuthorName'] = this.state.AuthorName;
    let response = await dynamicsService.AddRegulation(parm.Obj)

    if(response.code === 200) {
      // if(response.ItemId) {
      //   this.UpdateData(response.ItemId)
      // } else {
      //   // let UPdeta = await Api._saveaddDataGuid(parm);
      //   // let { form } = this.state;
      //   // form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
      //   // form.examination = '无'
      //   // form.proposal = '无'
      //   // this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
      //   this.setState({
      //     form: response.data,
      //     JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效'
      //   })
      // }
      let reviewOnxuan = []
      let reviewOn = []
      if (response.data.ReviewOn != null) {
        if (response.data.ReviewOn.indexOf(';') != -1) {
          let arrays = response.data.ReviewOn.split(';')
          for (let i = 0; arrays.length > i; i++) {
            reviewOnxuan.push(Number(arrays[i].split('#')[0]))
            reviewOn.push(arrays[i].split('#')[1])
          }
        } else {
          reviewOnxuan.push(Number(response.data.ReviewOn.split('#')[0]))
          reviewOn.push(response.data.ReviewOn.split('#')[1])
        }
      }
    let form = {
        contract: response.data.Title, //编号
        date: response.data.AcceptTime == null ? null : moment(response.data.AcceptTime).format('YYYY/MM/DD'),//法务受理日
        language: response.data.Language,//语言
        problem: response.data.Question,//问题
        date1: response.data.LastAnswerTime == null ? null : moment(response.data.LastAnswerTime).format('YYYY/MM/DD'),//法务最后回答
        nature: response.data.RegulationsCatalog,//规定分类
        theContract: response.data.RegulationsName,//规定名称
        qualificationss: response.data.ModifyNature ? response.data.ModifyNature.split(',') : [],//修改性质
        otherSide: response.data.RegulationsNum,//规定编号
        examination: response.data.LawyerReview,//律师审查 
        we: response.data.BelongsCompany, //规定所属公司
        cutNumber: response.data.RuleNumber,//决裁编号
        community: response.data.RelierName,//社内依赖者
        reviewOnxuans: response.data.ReviewOn,//审查担当
        file: response.data.FileAddress,//文件保存路径
        other: response.data.Other,//其它 
        proposal:response.data.HasReviewOpinion,//申请书
        reviewOnxuan: reviewOnxuan,
        reviewOn: reviewOn,
        versionNum: response.data.VersionNum,// 版本号
        // enclosurelist: response.data.Names == null ? [] : response.data.Names.split(';')
    }
      this.setState({
        form: form,
        JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效',
        loading: false
      })
      this.props.form.setFieldsValue({
        contract: response.title
      })
      this.setState({
        currentForm: response.data
      })
    } else {
      this.setState({
        loading: false
      })
      message.warning(response.msg);
    }
    
  }
  //生成编号
  private generateNumber = async (e) => {
    this.setState({
      variable: '有效'
    }, () => {
      e.preventDefault();
      this.props.form.validateFields(['data', 'text', 'theContract'], async (err, values) => {
        if (!err) {
          let paten = /^[A-Za-z]+$/g;
          if(!paten.test(this.state.form.we)) return;
          // this.getcurrentUser()
          // var param = {
          //   Guid: ListGUID.Regulations, //
          //   Filter: `BelongsCompany eq '${this.state.form.we}' and  AcceptYear eq '${Number(this.state.form.date.substring(0, 4))}' and  RegulationsStatus eq '废弃' and VersionNum eq '0'`
          // };
          // let Persons = await Api._getModel(param);

          // --------
          // var param = [
          //   {
          //     logic: "and",
          //     where: [
          //       {
          //         key: 'BelongsCompany',
          //         filterType: "Eq",
          //         value: this.state.form.we
          //       },
          //       {
          //         key: 'AcceptYear',
          //         filterType: "Eq",
          //         value: this.state.form.date.substring(0, 4)
          //       },
          //       {
          //         key: 'RegulationsStatus',
          //         filterType: "Eq",
          //         value: '废弃'
          //       },
          //       {
          //         key: 'VersionNum',
          //         filterType: "Eq",
          //         value: '0'
          //       }
          //     ]
          //   }
          // ]
          // let data1 = await Api._getPaged2({ Guid: ListGUID.Regulations, PageSize: 100000, PageIndex: 1, FilterL: param })
          // let Persons = data1.data;
          // if (Persons.length != 0) {
          //   let array = []
          //   Persons.forEach(element => {
          //     array.push({
          //       Titles: element.Title,
          //       Title: Number(element.Title.substring(0, element.Title.lastIndexOf('-')).substr(-3)),
          //       ID: element.ID
          //     })
          //   });
          //   array.sort(function (a, b) {
          //     return a.Title - b.Title  //正序
          //   })
          //   //获取废弃的编号
          //   let { form } = this.state;
          //   form.contract = array[0].Titles;
          //   this.props.form.setFieldsValue({
          //     contract: array[0].Titles
          //   });
          //   setTimeout(() => {
          //     form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
          //     // form.file = '合同/'+this.state.form.we+'/'+this.state.form.date.substring(0,4)+'/'+this.state.form.contract;
          //     form.examination = '无'
          //     form.proposal = '无'
          //     this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
          //     this.setState({
          //       form,
          //       JudgmentVariableID: this.state.JudgmentVariableID != null ? this.state.JudgmentVariableID : array[0].ID,
          //       JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '废弃',
          //       discardID:this.state.DraftNo == null ? null : array[0].ID,//草稿 启用废弃编号 获取id
          //     }, () => {
          //       this.UpdateData(array[0].ID)
          //     })
          //     
          //   }, 300);

          //   return;
          // }
          // -------

          // var param1 = {
          //   Guid: ListGUID.Regulations, //台账
          //   Filter: `BelongsCompany eq '${this.state.form.we}' and  AcceptYear eq '${this.state.form.date.substring(0, 4)}' and  RegulationsStatus eq '有效' and VersionNum eq '0'`
          // };
          // let Person = await Api._getModel(param1);
          
          if (this.state.currentForm) {
            
            if(!this.state.currentForm.Title.includes('DUMY')) {
              this.setState({
                currentForm: {
                  ...this.state.currentForm,
                  Title: ''
                }
                
              })
              let { form } = this.state;
              //获取当前登录人
              let Loggedby = await Api._getcurrentUser();
              this.state.personreviewList.forEach(element => {
                if (Loggedby.Id === element.ReviewUserId) {
                  form.reviewOnxuan = []
                  form.reviewOnxuan.push(element.Id)
                  form.reviewOn = element.Title
                  form.reviewOnxuans = `${element.Id}#${element.Title}`
                }
              });
              this.setState({
                form
              }, () => {
                this.AddData()
              })
            } else {
              this.UpdateData(this.state.currentForm.ItemId)
            }
          } else {
            this.AddData()
          }
          // if(this.state.currentForm) {
          //   if(this.state.currentForm.Title) {
          //     if(!this.state.currentForm.Title.includes('DUMY')) {
          //       this.AddData()
          //     } else {
          //       this.UpdateData(this.state.currentForm.ItemId)
          //     }
              
          //   } else {
          //     this.UpdateData(this.state.currentForm.ItemId)
          //   }
          // } else {
          //   this.AddData()

          //   // ---------------------------
          //   // var param = [
          //   //   {
          //   //     logic: "and",
          //   //     where: [
          //   //       {
          //   //         key: 'BelongsCompany',
          //   //         filterType: "Eq",
          //   //         value: this.state.form.we
          //   //       },
          //   //       {
          //   //         key: 'AcceptYear',
          //   //         filterType: "Eq",
          //   //         value: this.state.form.date.substring(0, 4)
          //   //       },
          //   //       {
          //   //         key: 'RegulationsStatus',
          //   //         filterType: "Eq",
          //   //         value: '有效'
          //   //       },
          //   //       {
          //   //         key: 'VersionNum',
          //   //         filterType: "Eq",
          //   //         value: '0'
          //   //       }
          //   //     ]
          //   //   }
          //   // ]
          //   // let data2 = await Api._getPaged2({ Guid: ListGUID.Regulations, PageSize: 100000, PageIndex: 1, FilterL: param })
          //   // let Person = data2.data
          //   // if (Person.length != 0) {
          //   //   let array = []
          //   //   Person.forEach(element => {
          //   //     array.push({
          //   //       Title: Number(element.Title.substring(0, element.Title.lastIndexOf('-')).substr(-3)),
          //   //       ID: element.ID
          //   //     })
          //   //   });
          //   //   array.sort(function (a, b) {
          //   //     return a.Title - b.Title  //正序
          //   //   })
          //   //   let { form } = this.state;
          //   //   form.contract = this.state.form.we + 'GD' + this.state.form.date.substring(0, 4) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3) + '-0';
          //   //   await this.setState({
          //   //     form
          //   //   });
          //   //   this.props.form.setFieldsValue({
          //   //     contract: this.state.form.we + 'GD' + this.state.form.date.substring(0, 4) + this.prefixZero(Number(array[array.length - 1].Title) + 1, 3) + '-0'
          //   //   })
          //   //   setTimeout(async () => {
          //   //     form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
          //   //     // form.file = '合同/'+this.state.form.we+'/'+this.state.form.date.substring(0,4)+'/'+this.state.form.contract;
          //   //     form.examination = '无'
          //   //     form.proposal = '无'
          //   //     this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
          //   //     this.setState({
          //   //       form,
          //   //       JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效'
          //   //     })
          //   //     //草稿生成编号 不创建
          //   //     if (this.state.DraftNo != null) return;
          //   //     var pa = {
          //   //       Guid: ListGUID.Regulations,
          //   //       Obj: {
          //   //         Title: this.state.form.contract, //编号
          //   //         AcceptTime: this.state.form.date ,//法务受理日
          //   //         RegulationsName: this.state.form.theContract,  //规定名称
          //   //         FileAddress: this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/',//文件保存路径
          //   //         BelongsCompany: this.state.form.we, //规定所属公司
          //   //         HasReviewOpinion:this.state.form.proposal,//申请书
          //   //         AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
          //   //         // VersionNum: this.state.form.versionNum,// 版本号
          //   //         // RegulationsStatus: '有效',//状态
          //   //         VersionNum: 0,
          //   //         RegulationsStatus: '有效',
          //   //       }
          //   //     };
          //   //     
          //   //     var result = await Api._saveaddDataGuid(pa);
          //   //   }, 300);
          //   //   return;
          //   // }
          //   // let { form } = this.state;
          //   // form.contract = this.state.form.we + 'GD' + this.state.form.date.substring(0, 4) + '001-0';
          //   // this.props.form.setFieldsValue({
          //   //   contract: this.state.form.we + 'GD' + this.state.form.date.substring(0, 4) + '001-0'
          //   // })
          //   // await this.setState({
          //   //   form
          //   // });
          //   // setTimeout(async () => {
          //   //   form.file = this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/';
          //   //   form.examination = '无'
          //   //   form.proposal = '无'
          //   //   this.Folder(this.state.form.we, this.state.form.date.substring(0, 4), this.state.form.contract)
          //   //   this.setState({
          //   //     form,
          //   //     JudgmentVariable: this.state.JudgmentVariableID != null ? this.state.JudgmentVariable : '有效'
          //   //   })
          //   //   //草稿生成编号 不创建
          //   //   if (this.state.DraftNo != null) return;
          //   //   var pa = {
          //   //     Guid: ListGUID.Regulations,
          //   //     Obj: {
          //   //       Title: this.state.form.contract, //编号
          //   //       AcceptTime: this.state.form.date,//法务受理日
          //   //       RegulationsName: this.state.form.theContract,  //规定名称
          //   //       FileAddress: this.state.form.date.substring(0, 4) + '/' + this.state.form.we + '/' + this.state.form.contract + '/',//文件保存路径
          //   //       BelongsCompany: this.state.form.we, //规定所属公司
          //   //       HasReviewOpinion:this.state.form.proposal,//申请书
          //   //       AcceptYear: this.state.form.date == null ? null : Number(this.state.form.date.substring(0, 4)),//受理日年份
          //   //       // VersionNum: this.state.form.versionNum,// 版本号
          //   //       // RegulationsStatus: '有效',//状态
          //   //       VersionNum: 0,
          //   //       RegulationsStatus: '有效',
          //   //     }
          //   //   };
          //   //   
          //   //   var result = await Api._saveaddDataGuid(pa);
          //   // }, 300);

          //    // ---------------------------
          // }
          
        }
      });
    })
    
    


  }
  //三位数 不足 补0
  public prefixZero(n, m) {
    var _a = (Array(m).join('0') + n).slice(-m);
    return _a;
  }
  //创建文件夹
  public async Folder(A, B, C) {
    let Persons2 = await Api.checkAndCreateFolder(`${ListGUID.RegulationsLibRelativeUrl}/${B}`)
    let Persons3 = await Api.checkAndCreateFolder(`${ListGUID.RegulationsLibRelativeUrl}/${B}/${A}`)
    let Persons4 = await Api.checkAndCreateFolder(`${ListGUID.RegulationsLibRelativeUrl}/${B}/${A}/${C}`)
  }
  //根据编号获取 数据 更新
  public async getedit(item) {
    // var param = {
    //   Guid: ListGUID.Regulations, //
    //   Filter: `Title eq '${item}'`
    // };
    // let Persons = await Api._getModel(param);
    this.setState({
      loading: true
    })
    let params: any = [
      {
        logic: "and",
        where: [
          {
            key: 'Title',
            filterType: "Eq",
            value: item
          }
        ]
      }
    ];
    let data = await Api._getPaged2({ Guid: ListGUID.Regulations, PageSize: 100000, PageIndex: 1, FilterL: params });
    let Persons = data.data;
    
    let reviewOnxuan = []
    let reviewOn = []
    if (Persons[0].ReviewOn != null) {
      if (Persons[0].ReviewOn.indexOf(';') != -1) {
        let arrays = Persons[0].ReviewOn.split(';')
        for (let i = 0; arrays.length > i; i++) {
          reviewOnxuan.push(Number(arrays[i].split('#')[0]))
          reviewOn.push(arrays[i].split('#')[1])
        }
      } else {
        reviewOnxuan.push(Number(Persons[0].ReviewOn.split('#')[0]))
        reviewOn.push(Persons[0].ReviewOn.split('#')[1])
      }
    }

    await this.setState({
      form: {
        contract: Persons[0].Title, //编号
        date: Persons[0].AcceptTime == null ? null : moment(Persons[0].AcceptTime).format('YYYY/MM/DD'),//法务受理日
        language: Persons[0].Language,//语言
        problem: Persons[0].Question,//问题
        date1: Persons[0].LastAnswerTime == null ? null : moment(Persons[0].LastAnswerTime).format('YYYY/MM/DD'),//法务最后回答
        nature: Persons[0].RegulationsCatalog,//规定分类
        theContract: Persons[0].RegulationsName,//规定名称
        qualificationss: Persons[0].ModifyNature ? Persons[0].ModifyNature.split(',') : [],//修改性质
        otherSide: Persons[0].RegulationsNum,//规定编号
        examination: Persons[0].LawyerReview,//律师审查 
        we: Persons[0].BelongsCompany, //规定所属公司
        cutNumber: Persons[0].RuleNumber,//决裁编号
        community: Persons[0].RelierName,//社内依赖者
        reviewOnxuans: Persons[0].ReviewOn,//审查担当
        file: Persons[0].FileAddress,//文件保存路径
        other: Persons[0].Other,//其它 
        proposal:Persons[0].HasReviewOpinion,//申请书
        reviewOnxuan: reviewOnxuan || [],
        reviewOn: reviewOn || [],
        versionNum: Persons[0].VersionNum
        // enclosurelist: Persons[0].Names == null ? [] : Persons[0].Names.split(';')
      },
      DraftNo: Persons[0].RegulationsStatus == '草稿' ? Persons[0].Title : null,
      JudgmentVariableID: Persons[0].ID,
      JudgmentVariable: Persons[0].RegulationsStatus == '有效' ? '废弃' : Persons[0].RegulationsStatus,
      wedisabled: Persons[0].RegulationsStatus == '草稿' ? false : true,
      time:Persons[0].AcceptYear,
      loading: false,
      currentForm: Persons[0]
    })
    
    this.props.form.setFieldsValue({
      data: Persons[0].AcceptTime == null ? null : moment(Persons[0].AcceptTime),
      data1: Persons[0].LastAnswerTime == null ? null : moment(Persons[0].LastAnswerTime)
    });
    await dynamicsService.UpdateListFileNames({dataid: Persons[0].id, listguid: ListGUID.Regulations, fileaddress: Persons[0].FileAddress})
  }
   // 关闭按钮触发
   public async shutDown () {
    let MinistryJustice = await Api._isLegalDepartment();
    confirm({
      centered: true,
      title: '温馨提示',
      content: `是否关闭该页面,关闭该页面未提交数据清空?`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // location.href = "#/Dashboard" 
        // 判断是否为法务部
        // MinistryJustice = false
        if (MinistryJustice) { location.href = "#/Dashboard"  } else {
          location.href = "#/DocumentLibrary"
        }
      }
    });
  }
}
export default Form.create()(Regulations);